﻿Imports System.Collections.Generic
Imports System.IO
Imports System.Xaml
Imports System.Xml

''' <summary></summary>
''' <remarks>
''' http://blogs.msdn.com/b/mwinkle/archive/2009/12/10/emitting-the-mc-ignorable-instruction-in-your-wf4-xaml.aspx
''' </remarks>
Public Class IgnorableXamlXmlWriter
    Inherits XamlXmlWriter

    Private ignorableNamespaces As New HashSet(Of NamespaceDeclaration)()
    Private allNamespaces As New HashSet(Of NamespaceDeclaration)()
    Private objectWritten As Boolean
    Private hasDesignNamespace As Boolean
    Private designNamespacePrefix As String

    Public Sub New(ByVal tw As TextWriter, ByVal context As XamlSchemaContext)
        MyBase.new(XmlWriter.Create(tw, New XmlWriterSettings With {.Indent = True, .OmitXmlDeclaration = True}),
                          context,
                          New XamlXmlWriterSettings With {.AssumeValidInput = True})
    End Sub

    Public Overrides Sub WriteNamespace(ByVal namespaceDeclaration As System.Xaml.NamespaceDeclaration)

        If Not objectWritten Then
            allNamespaces.Add(namespaceDeclaration)
            If namespaceDeclaration.Namespace = "http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" Then
                hasDesignNamespace = True
                designNamespacePrefix = namespaceDeclaration.Prefix
                'Else
                '    Console.WriteLine("WriteNamespace : " + namespaceDeclaration.Prefix + " " + namespaceDeclaration.Namespace)
            End If
        End If

        MyBase.WriteNamespace(namespaceDeclaration)
    End Sub

    Public Overrides Sub WriteStartObject(ByVal type As System.Xaml.XamlType)

        'Console.WriteLine("WriteStartObject : " + type.Name)

        If Not objectWritten Then
            If hasDesignNamespace Then
                Dim mcAlias = "mc"
                WriteNamespace(New NamespaceDeclaration("http://schemas.openxmlformats.org/markup-compatibility/2006", mcAlias))
                'Else
                '    Console.WriteLine("  No hasDesignNamespace : ")
            End If
        End If

        MyBase.WriteStartObject(type)

        If Not objectWritten Then
            If hasDesignNamespace Then
                Dim ign As New XamlDirective("http://schemas.openxmlformats.org/markup-compatibility/2006", "Ignorable")
                WriteStartMember(ign)
                WriteValue(designNamespacePrefix)
                WriteEndMember()
                objectWritten = True
                'Else
                '    Console.WriteLine("  No hasDesignNamespace After WriteStartObject : ")
            End If
        End If

    End Sub

End Class
